package com.pai4j.message.factory;

import com.pai4j.common.enums.InteractionMessageTypeEnum;
import com.pai4j.domain.vo.dto.BaseMessageDTO;
import com.pai4j.message.core.builder.MessageBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 消息构建器工厂
 * 管理和提供MessageBuilder实例
 *
 * @author PAI4J Team
 * @date 2025-11-01
 */
@Slf4j
public class MessageBuilderFactory {

    /**
     * 构建器映射表
     * key: 消息类型
     * value: 构建器类
     */
    private static final Map<InteractionMessageTypeEnum, Class<? extends MessageBuilder<?>>> BUILDER_CLASS_MAP = 
            new ConcurrentHashMap<>();

    /**
     * 构建器实例缓存（原型模式，每次创建新实例）
     */
    private static final Map<Class<?>, MessageBuilder<?>> BUILDER_PROTOTYPE_MAP = new ConcurrentHashMap<>();

    /**
     * 注册构建器
     */
    public static synchronized void register(InteractionMessageTypeEnum type, 
                                             Class<? extends MessageBuilder<?>> builderClass) {
        if (type == null || builderClass == null) {
            log.warn("注册参数不能为null: type={}, builderClass={}", type, builderClass);
            return;
        }

        BUILDER_CLASS_MAP.put(type, builderClass);
        log.info("注册MessageBuilder成功: type={}, class={}", type, builderClass.getSimpleName());
    }

    /**
     * 注册构建器实例（用于原型复制）
     */
    public static synchronized void registerPrototype(InteractionMessageTypeEnum type, 
                                                      MessageBuilder<?> prototype) {
        if (type == null || prototype == null) {
            log.warn("注册参数不能为null: type={}, prototype={}", type, prototype);
            return;
        }

        BUILDER_PROTOTYPE_MAP.put(prototype.getClass(), prototype);
        BUILDER_CLASS_MAP.put(type, (Class<? extends MessageBuilder<?>>) prototype.getClass());
        log.info("注册MessageBuilder原型成功: type={}, class={}", type, prototype.getClass().getSimpleName());
    }

    /**
     * 获取构建器
     */
    @SuppressWarnings("unchecked")
    public static <T extends BaseMessageDTO> MessageBuilder<T> getBuilder(InteractionMessageTypeEnum type) {
        if (type == null) {
            log.warn("消息类型不能为null");
            return null;
        }

        Class<? extends MessageBuilder<?>> builderClass = BUILDER_CLASS_MAP.get(type);
        if (builderClass == null) {
            log.warn("未找到MessageBuilder: type={}", type);
            return null;
        }

        try {
            // 创建新实例
            MessageBuilder<?> builder = builderClass.getDeclaredConstructor().newInstance();
            return (MessageBuilder<T>) builder;
        } catch (Exception e) {
            log.error("创建MessageBuilder失败: type={}, class={}, error={}", 
                    type, builderClass.getName(), e.getMessage(), e);
            return null;
        }
    }

    /**
     * 判断是否支持指定类型
     */
    public static boolean supports(InteractionMessageTypeEnum type) {
        return BUILDER_CLASS_MAP.containsKey(type);
    }

    /**
     * 获取所有已注册的类型
     */
    public static java.util.Set<InteractionMessageTypeEnum> getAllTypes() {
        return new java.util.HashSet<>(BUILDER_CLASS_MAP.keySet());
    }

    /**
     * 清空所有注册
     */
    public static synchronized void clear() {
        BUILDER_CLASS_MAP.clear();
        BUILDER_PROTOTYPE_MAP.clear();
        log.info("清空所有MessageBuilder注册");
    }

    /**
     * 获取注册统计信息
     */
    public static String getFactoryInfo() {
        StringBuilder info = new StringBuilder("MessageBuilderFactory Info:\n");
        info.append("Total Builders: ").append(BUILDER_CLASS_MAP.size()).append("\n");
        for (Map.Entry<InteractionMessageTypeEnum, Class<? extends MessageBuilder<?>>> entry : 
                BUILDER_CLASS_MAP.entrySet()) {
            info.append("  - ").append(entry.getKey()).append(": ")
                .append(entry.getValue().getSimpleName()).append("\n");
        }
        return info.toString();
    }
}

